package com.yyl.fmall.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @BelongsProject: fmall
 * @BelongsPackage: com.yyl.fmall.websocket
 * @Author: YuanSir
 * @CreateTime: 2022-11-11  15:07
 * @Description:
 * @Version: 1.0
 */


@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketServer {
    
    
    public static HashMap<String, Session> orderIdSessionMap = new HashMap<>();
    
    //private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    
    /**前端发送请求建立websocket连接，就会执行@OnOpen方法**/
    @OnOpen
    public void open(@PathParam("oid") String oid, Session session){
        orderIdSessionMap.put(oid,session);
    }
    
    /**前端关闭页面或者主动关闭websocket连接，都会执行close**/
    @OnClose
    public void close(@PathParam("oid") String orderId) throws IOException {
        Session session = orderIdSessionMap.get(orderId);
        session.close();
        orderIdSessionMap.remove(orderId);
    }
    
    /**
     * 推送消息的静态方法
     * @param orderId 订单编号
     * @param msg 要推送的消息
     */
    public static void sendMsg(String orderId, String msg){
        try {
            Session session = orderIdSessionMap.get(orderId);
            session.getBasicRemote().sendText(msg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
